package com.example.juc.until;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class  Sh{
    private static int number=0;
    private Lock lock =new ReentrantLock();
    Condition condition=lock.newCondition();

    public void jia() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0) {
                condition.await();  //睡眠  和wait一样
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "::" + number);
            condition.signalAll();   //唤醒和notifyAll一样
        }finally {
            lock.unlock();
        }
    }

    public void jian() throws InterruptedException {
        lock.lock();
        try {
            while (number != 1) {
                condition.await();  //睡眠  和wait一样
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"::"+number);
            condition.signalAll();   //唤醒和notifyAll一样
        }finally {
            lock.unlock();
        }
    }
}
public class Ljiajian {
    public static void main(String[] args) {
        Sh sh =new Sh();
        new Thread(() -> {
            for (int i = 1; i <11 ; i++) {
                try {
                    sh.jia();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();

        new Thread(() -> {
            for (int i = 1; i <11 ; i++) {
                try {
                    sh.jian();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();

        new Thread(() -> {
            for (int i = 1; i <11 ; i++) {
                try {
                    sh.jia();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();

        new Thread(() -> {
            for (int i = 1; i <11 ; i++) {
                try {
                    sh.jian();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"DD").start();
    }
}
